<template>
    <div>
        <div style="float:right;margin-right: 20px;">
              <el-button
              type="success"
              v-if="showbtnadd"
              @click="handleAdd"
            >添加</el-button>
        </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="setname" label="套餐名称"></el-table-column>
        <el-table-column prop="store_name" label="门店"></el-table-column>
        <el-table-column prop="num" label="数量"></el-table-column>
        <el-table-column prop="code" label="活动码"></el-table-column>
        <el-table-column prop="start_time" label="开始时间"></el-table-column>
        <el-table-column prop="end_time" label="结束时间"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              v-if="showbtnedit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              v-if="showbtndel"
              @click="handleDel(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width:100%;text-align:center;margin:50px auto;">
        <el-pagination
              background
              :page-sizes="[10, 20, 50, 100]"
              :page-size="10"
              layout="total,prev, sizes, pager, next, jumper"
              :total="totle"
              @size-change="handleSizeChange"
              @current-change="fenyeBtn"
        ></el-pagination>
      </div>
      <el-dialog title="添加" :visible.sync="addtypeDialog" width="50%" @close="closeDialogadd()">
        <el-form
          ref="addformInfo"
          :model="addformInfo"
          class="demo-form-inline"
          :rules="rules"
          label-width="100px"
        >
        <el-form-item prop="store_name" label="门店">
            <el-select v-model="addformInfo.store_name" style="width:50%" @change="changestores" placeholder="请选择">
            <el-option
              v-for="item in store_list"
              :key="item.id"
              :label="item.store_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="setname" label="套餐名称">
        <el-select v-model="addformInfo.setname" style="width:50%" @change="changeseats" placeholder="请选择">
            <el-option
              v-for="item in package_list"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <div v-if="isdaynum">
          <el-radio-group v-model="radio1" @change="radiochang">
          <div class="flexwap" v-for="(item,index) in daynumlist" :key="index">
          <el-form-item label="天数">
            <el-input disabled v-model="item.day">
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input disabled v-model="item.price">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
           <el-radio style="margin-left:20px" :label="item.set_day_id" border>选择此套餐</el-radio>
        </div>
          </el-radio-group>
        </div>
        <el-form-item prop="num" label="数量">
            <el-input v-model="addformInfo.num"></el-input>
        </el-form-item>
        <!-- <el-form-item prop="code" label="活动码">
            <el-input v-model="addformInfo.code"></el-input>
        </el-form-item> -->
        <el-form-item prop="times" label="选择日期">
            <el-date-picker format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" @change="addchangedatetime" v-model="addformInfo.times" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
          <el-form-item style="text-align: right;">
            <el-button @click="addtypeDialog=false">取消</el-button>
            <el-button type="primary" @click="submitFormadd('addformInfo')">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog title="编辑" :visible.sync="edittypeDialog" width="50%" @close="closeDialog()">
        <el-form
          ref="formInfo"
          :model="formInfo"
          class="demo-form-inline"
          :rules="rule"
          label-width="100px"
        >
        <el-form-item prop="store_name" label="门店">
            <!-- <el-input v-model="formInfo.store_name"></el-input> -->
            <el-select v-model="formInfo.store_name" style="width:50%" disabled @change="changestores" placeholder="请选择">
            <el-option
              v-for="item in store_list"
              :key="item.id"
              :label="item.store_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="setname" label="套餐名称">
        <!-- <el-input v-model="formInfo.setname"></el-input> -->
        <el-select v-model="formInfo.setname" style="width:50%" disabled @change="changeseats" placeholder="请选择">
            <el-option
              v-for="item in package_list"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <div v-if="formInfo.type==1">
           <el-radio-group>
          <div class="flexwap">
          <el-form-item label="天数">
            <el-input disabled v-model="editseallist.day">
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input disabled v-model="editseallist.price">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </div>
          </el-radio-group>
        </div>
        <el-form-item prop="num" label="数量">
            <el-input v-model="formInfo.num" disabled></el-input>
        </el-form-item>
        <!-- <el-form-item prop="code" label="活动码">
            <el-input v-model="formInfo.code"></el-input>
        </el-form-item> -->
        <el-form-item prop="times" label="选择日期">
            <el-date-picker format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" v-model="formInfo.times" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="editchangedatetime"></el-date-picker>
        </el-form-item>
          <el-form-item style="text-align: right;">
            <el-button @click="edittypeDialog=false">取消</el-button>
            <el-button type="primary" @click="submitForm('formInfo')">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </template>
  <script>
  import {
    lists,
    activity,
    activityAdd,
    meituanactivityEdit,
    meituanactivityDel,
    setmeal
  } from "@/api/user";
import { adminStore } from "@/api/menu";
  import Base64 from "@/utils/base";
  import { getp_id } from "@/utils/getmenuid";
  export default {
    inject: ["reload"],
    data() {
      return {
        fileLists: [],
        isdaynum: false,
        radio1:"",
        radio2:"",
        typeid:"",
        daynumlist:"",
        editseallist:"",
        cardday:"",
        cardprice:"",
        page:1,
        totle:10,
        num:10,
        allpath: [],
        formInfo: {
            setname:"",
            store_name:"",
            num:"",
            // code:"",
            times:[],
            id:"",
            store_id: "",
            setmeal_id :""
        },
        addformInfo:{
            setname:"",
            store_name:"",
            num:"",
            // code:"",
            times:[]
        },
        rules: {
            store_name: [{ required: true, message: "请选择门店", trigger: "change" }],
            setname: [{ required: true, message: "请选择套餐", trigger: "change" }],
            num: [{ required: true, message: "请输入数量", trigger: "blur" }],
            // code: [{ required: true, message: "请输入活动码", trigger: "blur" }],
            times: [{ required: true, message: "请选择日期时间", trigger: "change" }],
        },
        rule:{
            store_name: [{ required: true, message: "请选择门店", trigger: "change" }],
            setname: [{ required: true, message: "请选择套餐", trigger: "change" }],
            num: [{ required: true, message: "请输入数量", trigger: "blur" }],
            // code: [{ required: true, message: "请输入活动码", trigger: "blur" }],
            times: [{ required: true, message: "请选择日期时间", trigger: "change" }],
        },
        package_list:"",//套餐列表
        store_list:"",
        dialogImageUrl: "",
        dialogVisiblepath: false,
        sortformInfo: "",
        // sortpopup: false,
        addtypeDialog: false,
        edittypeDialog: false,
        atlaspopup: false,
        tableData: "",
        page: 1,
        showbtnedit:false,
        showbtnadd:false,
        showbtndel:false,
        genre_id: ""
        // edittimes:[]
      };
    },
    created() {
      this.getlists();
      setTimeout(() => {
        this.getactivitylist();
      }, 500);
    },
    methods: {
      getactivitylist(page,num) {
        let parmes = {
            page: page || this.page,
            limit: num || this.num,
            store_id:JSON.parse(localStorage.getItem("storemenu"))[0].id != ""
        ? JSON.parse(localStorage.getItem("storemenu"))[0].id
        : 0
        }
        activity({
              request_data: Base64.encode(JSON.stringify(parmes))
        }).then(res => {
          this.tableData = res.result.data
          this.totle = res.result.count
        })
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisiblepath = true;
      },
      handleRemove(file, fileList) {
        const filePath = file.response.file_path;
        // 2.从pictureList数组中，找到图片对应的索引值
        const i = this.allpath.findIndex(x => x == filePath);
        // 3.调用splice方法，移除图片信息
        this.allpath.splice(i, 1);
      },
      handcardsuccess(res, file) {
        // if (typeof this.fileLists[0] == "object") {
        //   this.fileLists.shift(this.fileLists);
        // }
        this.allpath.push(res.file_path);
      },
      radiochang(e){
      this.radio1 = e
      this.daynumlist.map(item => {
          //model就是上面的数据源
          if(item.set_day_id == e){
            this.cardday = item.day
            this.cardprice = item.price
          }
          // return item.id === event; //筛选出匹配数据
        });
    },
      beforeAvatarUpload(file) {
        const isJPG = file.type === "image/jpeg" || file.type == "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
          return;
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
          return;
        }
      },
      getlists() {
        lists({
          request_data: Base64.encode(JSON.stringify({ pid: getp_id() }))
        }).then(res => {
          if(res.status==2){
            this.$message({
              message:res.message,
              type:'warning'
            })
            return
          }
          let btnarr = [];
          res.result.map(v => {
            btnarr.push(v.class_mark);
          });
          btnarr.forEach(item => {
            if (item == "system_42") {
              this.showbtnadd = true;
            }
            if (item == "system_43") {
              this.showbtnedit = true;
            }
            if (item == "system_44") {
              this.showbtndel = true;
            }
          });
        });
      },
      addchangedatetime(e){
        // console.log(e,"111")s
      },
      //编辑时间日期
      editchangedatetime(e){
        this.formInfo.times[0]=e[0]
        this.formInfo.times[1]=e[1]
      },
      //添加
      handleAdd() {
        this.addtypeDialog = true;
        this.store_list =
      JSON.parse(localStorage.getItem("storemenu"))[0].id != ""
        ? JSON.parse(localStorage.getItem("storemenu"))
        : this.getadminStore();
      },
      getadminStore() {
      adminStore({
        request_data: Base64.encode(JSON.stringify({ store_id: "" }))
      }).then(res => {
         if(res.status==2){
          this.$message({
            message:res.message,
            type:'warning'
          })
          return
        }
        this.store_list = res.data;
        return res.data
      });
    },
    //选择门店
    changestores(e){
        this.getsetmeal(e)
        this.typeid = ""
        this.store_id = e
        this.formInfo.setname = ""
        this.addformInfo.setname = ""
        this.isdaynum = false
        this.cardday = ""
        this.cardprice = ""
        this.radio1 = ""
    },
    //选择套餐
    changeseats(e){
      this.package_id = e
      let obj = {};
      this.radio1 = ""
      obj = this.package_list.find(item => {
        //model就是上面的数据源
        return item.id === e; //筛选出匹配数据
      })
      this.typeid = obj.type
      if (obj.type == 1) {
        this.isdaynum = true;
        this.daynumlist = obj.set
      } else {
        this.isdaynum = false;
      }
    },
    getsetmeal(val){
        let parmes = {
            store_id:val
        }
      setmeal({
        request_data: Base64.encode(JSON.stringify(parmes))
      }).then(res => {
         if(res.status==2){
          this.$message({
            message:res.message,
            type:'warning'
          })
          return
        }
        this.package_list = res.result
      })
    },
    //编辑
    handleEdit(val) {
      this.edittypeDialog = true
      this.store_list =
      JSON.parse(localStorage.getItem("storemenu"))[0].id != ""
        ? JSON.parse(localStorage.getItem("storemenu"))
        : this.getadminStore();
        this.getsetmeal(val.store_id)
        this.formInfo.setname = val.setname
        this.formInfo.store_name = val.store_name
        this.formInfo.num = val.num
        this.formInfo.id = val.id
        this.formInfo.store_id = val.store_id
        this.formInfo.setmeal_id = val.setmeal_id
        // this.formInfo.code = val.code
        this.formInfo.times[0] = val.start_time
        this.formInfo.times[1] = val.end_time
        if(val.type==1){
          this.editseallist = val.set
        }
    },
    handleDel(val) {
        this.$confirm("确定删除此条数据吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            meituanactivityDel({
              request_data: Base64.encode(JSON.stringify({ id: val.id }))
            }).then(res => {
              if(res.status==2){
            this.$message({
              message:res.message,
              type:'warning'
            })
            return
          }
              this.getactivitylist();
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      },
      // 关闭弹框
      closeDialog() {
        this.$refs["formInfo"].resetFields();
        this.edittypeDialog = false;
      },
      closeDialogadd() {
        this.$refs["addformInfo"].resetFields();
        this.store_list = ""
        this.package_list = ""
        this.addtypeDialog = false;
        this.isdaynum = false
      },
      showatlas(val) {
        this.genre_id = val.id;
        if (val.img) {
          let objimg = val.img;
          objimg.forEach(item => {
            let obj = {
              url: item.img
            };
            this.fileLists.push(obj);
          });
        }
        this.atlaspopup = true;
      },
      submitFormadd(formName){
        this.$refs[formName].validate(valid => {
          if (valid) {
            if(this.typeid!=1){
              this.radio1="0"
              var postparmes = {
                set_day_id:this.radio1,
                store_id:this.store_id,
                setmeal_id:this.package_id,
                num:this.addformInfo.num,
                start_time:this.addformInfo.times[0],
                end_time:this.addformInfo.times[1]
            }
            }else{
              if(this.radio1==""){
                this.$message({
                    message:"请选择套餐",
                    type:'warning'
                })
                return
              }
              var postparmes = {
                set_day_id:this.radio1,
                store_id:this.store_id,
                setmeal_id:this.package_id,
                num:this.addformInfo.num,
                start_time:this.addformInfo.times[0],
                end_time:this.addformInfo.times[1]
            }
            }
            activityAdd({
              request_data: Base64.encode(JSON.stringify(postparmes))
            }).then(res => {
              if(res.status==2){
                this.$message({
                    message:res.message,
                    type:'warning'
                })
              return
            }
              this.closeDialogadd()
              this.getactivitylist()
            });
            // 走保存请求
          } else {
            return false;
          }
        });
      },
      // 保存操作
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let parmes = {
                id: this.formInfo.id,
                store_id: this.formInfo.store_id,
                setmeal_id: this.formInfo.setmeal_id,
                num: this.formInfo.num,
                start_time: this.formInfo.times[0],
                end_time: this.formInfo.times[1]
            };
            meituanactivityEdit({
              request_data: Base64.encode(JSON.stringify(parmes))
            }).then(res => {
              if(res.status==2){
            this.$message({
              message:res.message,
              type:'warning'
            })
            return
          }
            this.closeDialog();
            this.getactivitylist()
            });
            // 走保存请求
          } else {
            return false;
          }
        });
      },
      handleSizeChange(val) {
        this.num = val;
        this.getactivitylist(this.page, this.num);
      },
      fenyeBtn(e) {
        this.page = e
        this.getactivitylist(this.page,this.num);
      },
    }
  }
  </script>
  <style scoped>
  .el-table td,
  .el-table th {
    padding-left: 20px;
  }
  .flexwap {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
}
  </style>
  